import React, { useState, useEffect } from 'react'
import { Card, Table, Button, Modal, Form, Input, Select, Tag, Space, message, Spin } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons'
import MainLayout from '../components/layout/MainLayout'
import { personnelAPI } from '../utils/api'

const { Option } = Select

interface Personnel {
  id: string
  name: string
  position: string
  department: string
  phone: string
  email: string
  status: string
  joinDate: string
  workHours?: string
}

export default function Personnel() {
  const [personnel, setPersonnel] = useState<Personnel[]>([])
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [editingPerson, setEditingPerson] = useState<Personnel | null>(null)
  const [form] = Form.useForm()

  // 获取人员列表
  const fetchPersonnel = async () => {
    setLoading(true)
    try {
      const response = await personnelAPI.getList()
      setPersonnel(response.data)
    } catch (error) {
      message.error('获取人员列表失败')
      console.error('Fetch personnel error:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchPersonnel()
  }, [])

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <div style={{
            width: 32,
            height: 32,
            borderRadius: '50%',
            backgroundColor: '#f0f0f0',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginRight: 8,
            fontSize: 14,
            color: '#666'
          }}>
            {text.charAt(0)}
          </div>
          {text}
        </div>
      )
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position'
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department'
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        let color = 'green'
        if (status === '请假') color = 'orange'
        if (status === '离职') color = 'red'
        return <Tag color={color}>{status}</Tag>
      }
    },
    {
      title: '入职时间',
      dataIndex: 'joinDate',
      key: 'joinDate'
    },
    {
      title: '离开时间',
      dataIndex: 'workHours',
      key: 'workHours'
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Personnel) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  const handleAdd = () => {
    setEditingPerson(null)
    form.resetFields()
    setModalVisible(true)
  }

  const handleEdit = (person: Personnel) => {
    setEditingPerson(person)
    form.setFieldsValue(person)
    setModalVisible(true)
  }

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个员工吗？',
      onOk: async () => {
        try {
          await personnelAPI.delete(id)
          message.success('删除成功')
          fetchPersonnel()
        } catch (error) {
          message.error('删除失败')
          console.error('Delete personnel error:', error)
        }
      }
    })
  }

  const handleSave = async () => {
    try {
      const values = await form.validateFields()
      setLoading(true)
      
      if (editingPerson) {
        // 编辑
        await personnelAPI.update(editingPerson.id, values)
        message.success('更新成功')
      } else {
        // 新增
        await personnelAPI.create(values)
        message.success('添加成功')
      }
      
      setModalVisible(false)
      form.resetFields()
      setEditingPerson(null)
      fetchPersonnel()
    } catch (error) {
      message.error('操作失败')
      console.error('Save personnel error:', error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <MainLayout>
      <Card 
        title="人员管理" 
        extra={
          <Space>
            <Button 
              icon={<ReloadOutlined />}
              onClick={fetchPersonnel}
              loading={loading}
            >
              刷新
            </Button>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              新增员工
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={personnel}
          rowKey="id"
          loading={loading}
          pagination={{ 
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
        />
      </Card>

      <Modal
        title={editingPerson ? '编辑员工' : '新增员工'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => {
          setModalVisible(false)
          form.resetFields()
          setEditingPerson(null)
        }}
        width={600}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            status: '在职'
          }}
        >
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          
          <Form.Item
            name="position"
            label="职位"
            rules={[{ required: true, message: '请输入职位' }]}
          >
            <Input placeholder="请输入职位" />
          </Form.Item>
          
          <Form.Item
            name="department"
            label="部门"
            rules={[{ required: true, message: '请选择部门' }]}
          >
            <Select placeholder="请选择部门">
              <Option value="技术研发部">技术研发部</Option>
              <Option value="产品部">产品部</Option>
              <Option value="设计部">设计部</Option>
              <Option value="人事部">人事部</Option>
              <Option value="财务部">财务部</Option>
              <Option value="市场部">市场部</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="phone"
            label="联系电话"
            rules={[
              { required: true, message: '请输入联系电话' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
            ]}
          >
            <Input placeholder="请输入联系电话" />
          </Form.Item>
          
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value="在职">在职</Option>
              <Option value="请假">请假</Option>
              <Option value="离职">离职</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="joinDate"
            label="入职时间"
          >
            <Input placeholder="请输入入职时间" />
          </Form.Item>
          
          <Form.Item
            name="workHours"
            label="工作时间"
          >
            <Input placeholder="请输入工作时间" />
          </Form.Item>
        </Form>
      </Modal>
    </MainLayout>
  )
}
